package com.zhangtai.eSign.HttpRest;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhangtai.eSign.entity.OutSideAccountEntity;
import com.zhangtai.eSign.pdf.ContractPdf;
import com.zhangtai.enums.ErrCodeEnum;
import com.zhangtai.modules.entity.contract.ContractModelEntity;
import com.zhangtai.modules.entity.contract.ProtocolEntity;
import com.zhangtai.modules.entity.contract.ProtocolPersonnelEntity;
import com.zhangtai.modules.entity.employee.EmployerCompanyEntity;
import com.zhangtai.modules.entity.employee.RelativeRecordsEntity;
import com.zhangtai.modules.vo.ExportContractPdfVo;
import com.zhangtai.utils.HmacSHA256;
import com.zhangtai.utils.R;
import com.zhangtai.utils.TypeCastUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ming
 * @Date: 2020/5/28 0028 下午 5:59
 */

@Service
@Slf4j
@RestController

public class HttpRest {
    private static final String url = "http://sign.zhangtai.com.cn:8035";
    private static final String projectKey = "1000032";  //项目id
    private static final String projectSecret = "82da0d2db4029905912836db0f4c25fd";  //项目秘钥
    private static final String uncheckProjectKey = "1000000";  //不需要验签的项目id
    private static final String uncheckSignature = "c054b2215990b107b7e0abc7a9b1a3e057ec79f424a7a809e3598e59191e59e0";  //不需要验签的项目秘钥
    private static final String createOutSideAccountUrl = url + "/V1/accounts/outerAccounts/create"; //创建外部用户
    private static final String uploadPdfUrl = url + "/V1/files/upload"; //上传文件url
    private static final String signfUrl = url + "/V1/signFlows/create";  //签合同url
    private static final String getContractUrl = url + "/V1/signFlows/getSignFlowDocUrls"; //获取合同rul
    private static final String queryOutsideUser = url + "/V1/accounts/outerAccounts/query"; //查询外部用户是否存在
    private static final String signFlows = url + "/V1/signFlows/signDetail"; //查询外部用户是否存在

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 查询外部用户
     *
     * @param idCard
     * @return
     */
    public R<String> queryOutsideUser(String idCard) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);  //请求头 multipart/form-data
        headers.set("x-timevale-project-id", uncheckProjectKey);  //请求头设置项目id
//        String s="{}"; //用空json做加密签名
//        String signature = HmacSHA256.sha256_HMAC(s, projectSecret); //将请求体内容用HmacSHA256和projectSecret作为秘钥进行加密作为签名
        headers.set("x-timevale-signature", uncheckSignature);  //请求头设置签名
        String url = queryOutsideUser + "?uniqueId=" + idCard;
        HttpEntity entity = new HttpEntity<>(headers);

        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class);
        JSONObject body = responseEntity.getBody();

        log.info("请求结果:{}", body);
        if (ObjectUtils.isEmpty(body)) {
            queryOutsideUser(idCard); //递归重试
//            return R.error("查询外部用户失败");
        }
        Integer errCode = body.getInteger("errCode");

        if (!errCode.equals(0)) {
            return R.error(body.getString("msg"));
        }
        JSONObject data = body.getJSONObject("data");
        String uniqueId = data.getString("uniqueId");

        if (StringUtils.isEmpty(uniqueId)) {
            queryOutsideUser(idCard); //递归重试
//            return R.error("获取外部用户为空");
        }

        return R.ok(uniqueId);

    }


    /**
     * 创建外部用户
     *
     * @param outSideAccountEntity
     * @return
     */

    public R<String> createOutSideAccount(OutSideAccountEntity outSideAccountEntity) throws InterruptedException {

//        log.info("outSideAccountEntity==============>>>>>>>>>>:{}",outSideAccountEntity);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);  //请求头 application/json
        headers.set("x-timevale-project-id", projectKey);  //请求头设置项目id
        String s = JSON.toJSONString(outSideAccountEntity);  //请求体
        String signature = HmacSHA256.sha256_HMAC(s, projectSecret); //将请求体内容用HmacSHA256和projectSecret作为秘钥进行加密作为签名
        headers.set("x-timevale-signature", signature);  //请求头设置签名
        HttpEntity<String> httpEntity = new HttpEntity<>(s, headers);
        log.info("请求体:{}", s);
        ResponseEntity<JSONObject> jsonObjectResponseEntity = restTemplate.postForEntity(createOutSideAccountUrl, httpEntity, JSONObject.class);
        JSONObject body = jsonObjectResponseEntity.getBody();

        if (ObjectUtil.isNull(body)) {
            return R.error(ErrCodeEnum.ESIGN_USER_FAIL.getCode(), "body为空");
        }
        Integer errCode = TypeCastUtils.toInt(body.get("errCode"));
        if (errCode == null) {
            log.info("e签宝创建用户失败：{}，重新创建", body);
            Thread.sleep(1000);
            createOutSideAccount(outSideAccountEntity);
//            return R.error(ErrCodeEnum.ESIGN_USER_FAIL.getCode(),"获取状态码为空");
        }

        JSONObject data = body.getJSONObject("data");
        String uniqueId = data.getString("uniqueId");

        if (StringUtils.isEmpty(uniqueId)) {
            log.info("e签宝创建用户失败：{},重新创建", body);

            Thread.sleep(1000);
            createOutSideAccount(outSideAccountEntity);

//            return R.error(ErrCodeEnum.GET_ESIGN_USER_FAIL);
        }
        if (!errCode.equals(0)) {
            String msg = body.getString("msg");
            log.info("e签宝创建用户失败：{}", body);
            return R.error(ErrCodeEnum.ESIGN_USER_FAIL.getCode(), msg);
        }

        log.info("e签宝创建用户返回：{}", body);
        return R.ok(uniqueId);


    }

    /**
     * 上传文件
     *
     * @param
     * @return
     */
    public R<String> upLoadNewPdf(String path) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);  //请求头 multipart/form-data
        headers.set("x-timevale-project-id", projectKey);  //请求头设置项目id
        String s = "{}"; //用空json做加密签名
        String signature = HmacSHA256.sha256_HMAC(s, projectSecret); //将请求体内容用HmacSHA256和projectSecret作为秘钥进行加密作为签名
        headers.set("x-timevale-signature", signature);  //请求头设置签名
        FileSystemResource file = new FileSystemResource(new File(path));
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("file", file);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        ResponseEntity<JSONObject> jsonObjectResponseEntity = restTemplate.postForEntity(uploadPdfUrl, httpEntity, JSONObject.class);
        JSONObject body = jsonObjectResponseEntity.getBody();
        if (ObjectUtils.isEmpty(body)) {
            return R.error();
        }
        Integer code = TypeCastUtils.toInt(body.get("errCode"));
        if (!code.equals(0)) {
            return R.error(body.getString("msg"));
        }

        JSONObject data = body.getJSONObject("data");
        String fileKey = data.getString("fileKey");
        File f = new File(path);
        if (f.exists()) {
            f.delete();
        }
//        log.info("fileKey:{}",fileKey);
        return R.ok(fileKey);
    }


    /**
     * 签合同
     *
     * @param s
     * @return
     */
    public R<Map<String, Object>> sign(String s) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);  //请求头 application/json
        headers.set("x-timevale-project-id", projectKey);  // 请求头封装项目id

        String signature = HmacSHA256.sha256_HMAC(s, projectSecret);
        headers.set("x-timevale-signature", signature);
        HttpEntity<String> httpEntity = new HttpEntity<>(s, headers);
        ResponseEntity<JSONObject> jsonObjectResponseEntity = restTemplate.postForEntity(signfUrl, httpEntity, JSONObject.class);
        JSONObject body = jsonObjectResponseEntity.getBody();
        if (ObjectUtil.isNull(body)) {
            return R.error("body为空");
        }
        Integer errCode = TypeCastUtils.toInt(body.get("errCode"));
        if (errCode == null) {

            return R.error("获取状态码为空");
        }
        if (!errCode.equals(0)) {
            String msg = body.getString("msg");
            log.info(msg);
            return R.error(msg);
        }
        JSONObject data = body.getJSONObject("data");
        JSONArray signDocs = data.getJSONArray("signDocs");
        JSONObject jsonObject = signDocs.getJSONObject(0);
        Integer docId = TypeCastUtils.toInt(jsonObject.get("docId"));
        JSONArray signUrls = data.getJSONArray("signUrls");
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("docId", docId);
        if (!CollectionUtils.isEmpty(signUrls)) {
            JSONObject urlsJSONObject = signUrls.getJSONObject(0);
            String signUrl = urlsJSONObject.getString("signUrl");
            hashMap.put("signUrl", signUrl);
        }
//        log.info("hashMap:{}",hashMap);


        return R.ok(hashMap);

    }

    /**
     * 获取合同下载地址
     *
     * @param signFlowId
     * @return
     */

    public R<String> getContractUrl(Integer signFlowId) {


        String url = getContractUrl + "?signFlowId={signFlowId}&intranetFlag={intranetFlag}";
//        String url=getContractUrl+"?signFlowId="+signFlowId+"&intranetFlag=N";


        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);  //请求头 application/json
        headers.set("x-timevale-project-id", uncheckProjectKey);  // 请求头封装项目id
//        String signature = HmacSHA256.sha256_HMAC("{}", projectSecret);
        headers.set("x-timevale-signature", uncheckSignature);

//        JSONObject object = new JSONObject();
        HttpEntity httpEntity = new HttpEntity<>(headers);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("signFlowId", signFlowId);
        hashMap.put("intranetFlag", "N");


        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JSONObject.class, hashMap);
//
        if (ObjectUtils.isEmpty(responseEntity)) {
            return R.error("请求失败");
        }
        JSONObject body = responseEntity.getBody();
        Integer errCode = TypeCastUtils.toInt(body.get("errCode"));
        if (!errCode.equals(0)) {
            log.info("获取下载地址失败:{}", body.toString());
            return R.error(body.getString("msg"));
        }
        JSONObject data = body.getJSONObject("data");
        JSONArray signDocUrlList = data.getJSONArray("signDocUrlList");
        JSONObject jsonObject = signDocUrlList.getJSONObject(0);
        String downloadDocUrl = jsonObject.getString("downloadDocUrl");


        return R.ok(downloadDocUrl);
    }

    /**
     * 根据流程id查询合同是否已签署
     *
     * @param flowId
     * @return
     */
    public R getSignDetail(Integer flowId) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);  //请求头 multipart/form-data
        headers.set("x-timevale-project-id", uncheckProjectKey);  //请求头设置项目id
//        String s="{}"; //用空json做加密签名
//        String signature = HmacSHA256.sha256_HMAC(s, projectSecret); //将请求体内容用HmacSHA256和projectSecret作为秘钥进行加密作为签名
        headers.set("x-timevale-signature", uncheckSignature);  //请求头设置签名
        String url = signFlows + "?signFlowId=" + flowId;
        HttpEntity entity = new HttpEntity<>(headers);

        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class);
        JSONObject body = responseEntity.getBody();
        if (ObjectUtils.isEmpty(body)) {
            return R.error("查询body为空");
        }
        JSONObject data = body.getJSONObject("data");
        if (ObjectUtils.isEmpty(data)) {
            return R.error("data查询为空");
        }
        JSONArray signers = data.getJSONArray("signers");
        if (CollectionUtils.isEmpty(signers)) {
            return R.error("查询signers为空");
        }
        for (Object signer : signers) {
            JSONObject object = JSON.parseObject(JSON.toJSONString(signer), JSONObject.class);
            String signResult = object.getString("signResult");
            if (!"签署成功".equals(signResult)) {
                return R.error();
            }

        }
        log.info("开始进行合同补偿url:{}", url);
        return R.ok(data);


    }

}
